package com.tgy.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: tgy
 * @Date: 12/8/20 10:26 AM
 */
public class _242_有效的字母异位词 {

    public boolean isAnagram(String s, String t) {

        if (s == null || t == null || t.length() != s.length()) {

            return false;
        }

        char[] chars = s.toCharArray();

        int[] counts = new int[26];

        for (char aChar : chars) {

            int index = aChar - 'a';
            counts[index] = counts[index] + 1;
        }

        for (char c : t.toCharArray()) {

            int index = c - 'a';

            if (--counts[index] < 0) {

                return false;
            }
        }

        return true;
    }

    public boolean isAnagram01(String s, String t) {

        if (s == null || t == null || t.length() != s.length()) {

            return false;
        }

        char[] chars = s.toCharArray();

        Map<Character,Integer> map = new HashMap<>();

        for (char aChar : chars) {

            map.put(aChar, map.getOrDefault(aChar,0) + 1);
        }

        for (char c : t.toCharArray()) {

            Integer count = map.get(c);
            if (count == null || count - 1 < 0) {

                return false;
            }

            map.put(c,count - 1);
        }

        return true;
    }
}
